from pymongo import MongoClient
# 数据库链接，必须保证当前系统能正常访问mongodb！！!
connect = MongoClient("mongodb://root:123@127.0.0.1:27017/admin")
my_db = connect["mofang"]
my_collections = my_db["my_collections"]

"""获取一条"""
# document = my_collections.find_one()
# print(document) # {'_id': 1, 'name': 'xiaoming1号', 'sex': True, 'age': 17}
# # 获取数据中的信息
# print(document["name"]) # xiaoming1号

"""获取多条数据"""
# document_list = my_collections.find()
# print(document_list) # <pymongo.cursor.Cursor object at 0x7fdabea815c0>
# for document in document_list:
#     print(document)
#     print(document["_id"]) # 获取信息


"""字段投影：只显示部分字段，1表示显示，0表示隐藏"""
# document_list = my_collections.find({},{"name":1,"_id":0})
# for document in document_list:
#     print(document)

"""基于查询条件获取数据"""
# 值相等
# query = {"name":{"$eq":"xiaoming"}}
# query = {"name":"xiaoming"}
# document = my_collections.find_one(query)
# print(document) # {'_id': ObjectId('5fd1e99089a3cb30ff48d13a'), 'name': 'xiaoming', 'mobile': '13012345678', 'age': 16, 'sex': True}

"""
query = {"age":{"$gt":17}}    age  >  17
query = {"age":{"$gte":17}}    age >= 17
query = {"age":{"$lte":17}}    age <= 17
query = {"age":{"$lt":17}}    age  <  17
query = {"age":{"$ne":17}}    age  != 17
query = {"age":{"$in":[16,17]}}    age in [16,17]
"""
# query = {"age":{"$in":[16,18]}}
# document_list = my_collections.find(query)
# for document in document_list:
#     print(document)

# 排序
"""
单个字段：
    sort("age",-1) # 倒序
    sort("age",1)  # 升序
多个字段：
    sort([("age",-1),("_id",1)])
"""
# document_list = my_collections.find().sort("age",-1)
# # document_list = my_collections.find().sort([("age",-1),("_id",1)])
# for document in document_list:
#     print(document)

"""限制结果"""
document_list = my_collections.find().limit(3)
for document in document_list:
    print(document)